Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Types of Inheritance

Multiple inheritance

Multiple inheritance is a feature of some object-oriented programming languages where a class can inherit properties and methods from more than one parent class. However, Java does not support multiple inheritance with classes due to potential issues such as the “diamond problem,” which occurs when a subclass inherits from two superclasses that have a method with the same signature. To overcome this limitation, Java provides a way to achieve multiple inheritance through interfaces. An interface in Java is a blueprint of a class that consists of static constants and abstract methods. A class can implement multiple interfaces, thereby inheriting the abstract methods of the interfaces. Here’s the syntax for a class implementing multiple interfaces:
interface basic syntax class MyClass implements Interface1, Interface2, Interface3 { // class body }
In this case, MyClass can inherit and implement methods from Interface1, Interface2, and Interface3. Here’s an example of how this works:
Example of multiple inheriatance in java through inheriatance interface Character { void attack(); } interface Weapon { void use(); } class Warrior implements Character, Weapon { public void attack() { System.out.println("Warrior attacks with a sword."); } public void use() { System.out.println("Warrior uses a sword."); } } class Mage implements Character, Weapon { public void attack() { System.out.println("Mage attacks with a wand."); } public void use() { System.out.println("Mage uses a wand."); } } public class MultipleInheritance { public static void main(String[] args) { Warrior warrior = new Warrior(); Mage mage = new Mage(); warrior.attack(); // Output: Warrior attacks with a sword. mage.attack(); // Output: Mage attacks with a wand. } }

Output

Warrior attacks with a sword. Mage attacks with a wand.
In this example, both Warrior and Mage classes implement the Character and Weapon interfaces, thereby achieving multiple inheritance.

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops ★ inheritance ★ Multiple inheritance

Tutorials